<?php
namespace app\api\controller;
use app\common\controller\HomeBase;
use app\common\model\Service;
use app\common\service\UploadService;

class Ajax extends HomeBase
{
    public function initialize()
    {
        parent::initialize();
        if(!session('userid')&&!session('admin.id')){
            return fail('未登录，无权限上传');
        }
    }
    /**
     * 上传文件
     */
    public function upload()
    {
        $File = $this->request->file('file');
        $data = $this->request->param();
        $watermark  = $uplodeType=$thumb = $dir='';

        if (isset($data['watermark'])) {
            $watermark = $data['watermark'];
        }
        if (!empty($data['upload_type'])) {
            $uplodeType = $data['upload_type'];
        }
        if (isset($data['thumb'])) {
            $thumb = $data['thumb'];
        }
        if (isset($data['type'])) {
            $dir = $data['type'];
        }else{
            $dir='uploads';
        }
        return UploadService::upfile($File, $uplodeType, $watermark, $thumb,$dir);
    }

    /**
     * 上传图片至编辑器
     * @return \think\response\Json
     */
    public function editorUploadImg()
    {
        $files = $this->request->file();
        $imags = [];
        $errors = [];
        $k = 0;
        $uploadConfig = sysconfig('upload');
        $maxSize = $uploadConfig['upload_allow_size'] * 1024 * 1024;
        $rule = [
            'file|文件' => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$maxSize}",
        ];
        foreach ($files as $file) {
            try {
                $this->validate(['file' => $file], $rule);
            } catch (\Exception $e) {
                array_push($errors, '文件大小或后缀不支持');
                continue;
            }
            $fileName = $file->getOriginalName();
            $picThumb = sysconfig('upload.picture_thumb_max');
            $res = UploadService::upfile($file, '', 1, $picThumb ? $picThumb : 700);
            if ($res['code'] == 1) {
                array_push($imags, [
                    'url' => $res['data']['url'],
                    'alt' => $fileName
                ]);
                $k++;
            } else {
                array_push($errors, @$res['msg']);
                continue;
            }
        }
        if (!empty($imags)) {
            $ret['errno'] = 0;
            $ret['data'] = $imags;
        } else {
            $ret['errno'] = 1;
            $ret['data'] = [];
            $ret['msg'] = "上传出错：" . implode('；', $errors);
        }
        return json($ret);
    }

    /**
     * 上传非图片（VIDEO）至编辑器
     * @return \think\response\Json
     */
    public function editorUploadFile()
    {
        $file = $this->request->file('file');
        $res = UploadService::upfile($file, '', 0, 0);
        if ($res['code'] == 1) {
            $res['errno'] = 0;
        } else {
            $ret['errno'] = 1;
        }
        return json($res);
    }

}